<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.keyword" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="入学年份">
              <a-select v-model="queryParam.year" placeholder="请选择入学年份" allowClear default-value="0">
                <a-select-option v-for="year in yearOptions" :value="year" :key="year">{{year}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="调用次数">
                <a-input-number v-model="queryParam.callNo" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="更新日期">
                <a-date-picker v-model="queryParam.date" style="width: 100%" placeholder="请输入更新日期"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select v-model="queryParam.useStatus" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px" v-if="false">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item>
          <!-- lock | unlock -->
          <a-menu-item key="2"><a-icon type="lock" />锁定</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
        </template>
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a @click="teacherSet(record)">老师设置</a>
            </a-menu-item>
            <a-menu-item>
              <a @click="studentSet(record)">学生设置</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;">教室设置</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;">课程表</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;">禁用</a>
            </a-menu-item>
            <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="delConfirm(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
  </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>
    <a-modal
      title="操作"
      :width="800"
      v-model="visible"
      @ok="handleOk"
    >
      <a-form :form="form">
         <a-form-item
           v-show="false"  
        >
          <a-input  style="width: 100%" v-decorator="[
          'id'
        ]" />
        </a-form-item>
   
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="班级名称"
          hasFeedback
        >
 <a-input style="width: 100%" v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入班级名称' }]}
        ]"
        placeholder="请输入班级名称"/>        
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="入学年级"
        >
          <a-select  v-decorator="[
              'year',
              {rules: [{ required: true, message: '请输入入学年级' }]}
              ]"
               placeholder="2019">
              <a-select-option v-for="year in findYearOptions" :value="year" :key="year">{{year}}</a-select-option>
          </a-select>
        </a-form-item>

        
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="教室"
        >
        <a-row type="flex" justify="space-between">
            <a-select @change="handleBuildingChange" style="width:180px"  v-decorator="[
              'buiding_id',
              {rules: [{ required: true, message: '请选择教学楼' }]}
              ]"
               placeholder="请选择教学楼">
            <a-select-option v-for="building in buildingOptions" :value="building.id" :key="building.id">{{building.name}}</a-select-option>
          </a-select>
          <a-select  style="width:180px"  v-decorator="[
              'classroomId',
              {rules: [{ required: true, message: '请选择教室' }]}
              ]"
               placeholder="请选择教室">
            <a-select-option v-for="room in roomOptions"  :value="room.id" :key="room.id">{{room.name}}</a-select-option>
          </a-select>
        </a-row>
        </a-form-item>
          <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="班级人数"
          hasFeedback
        >
 <a-input style="width: 100%" v-decorator="[
          'studentCount',
          {rules: [{ required: true, message: '请输入班级人数' }]}
        ]"
        placeholder="请输入班级人数"/>        
        </a-form-item>

         <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="学校等级"
        >
          <a-select  
              v-decorator="[
              'type',
              {rules: [{ required: true, message: '请输入学校等级' }]}
              ]"
               placeholder="请输入学校等级"
          >
            <a-select-option :value="0">小学</a-select-option>
            <a-select-option :value="1">初中</a-select-option>
             <a-select-option :value="2">高中</a-select-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="宣言"
          hasFeedback
          help="请填写一段宣言"
        >
          <a-textarea :rows="5"/>
        </a-form-item> -->


      </a-form>
    </a-modal>
    <!-- 教师设置 -->
    <a-modal
      title="操作"
      :width="800"
      v-model="teacherShow"
      @ok="handleTeacher"
    > 
      <a-form :form="teacherForm">
          
     <a-form-item
      v-for="(teacherRow, index) in teacherListData.teacherList"
      :key="teacherRow"
      v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
     >
          <a-select  
              v-model ='teacherRow.teacherId'
              allowClear
               placeholder="请输入授课老师"
            style="width: 30%; margin-right: 8px" > 
            <a-select-option 
             v-for="(teacherOption,tindex) in teacherOptions" :key="tindex"
              :value="teacherOption.id" >{{teacherOption.name}}</a-select-option> 
          </a-select>
         <a-select  
              v-model ='teacherRow.position'
              allowClear
               placeholder="请输入职位"
        style="width: 30%; margin-right: 8px" >
               <a-select-option 
             v-for="(teacherPositionOption,pindex) in teacherPositionOptions" :key="pindex"
              :value="teacherPositionOption.value" >{{teacherPositionOption.name}}</a-select-option> 
          </a-select>
                <a-select 
                  v-model ='teacherRow.course'
              allowClear
               v-if="typeof teacherRow.position != 'undefined' && teacherRow.position > 1"
               placeholder="请输入学科科目"
        style="width: 30%; margin-right: 8px">
          <a-select-option 
             v-for="(courseOption,cindex) in courseOptions" :key="cindex"
              :value="courseOption.value" >{{courseOption.name}}</a-select-option> 
          </a-select> 
      <a-icon
        class="dynamic-delete-button"
        type="minus-circle-o"
        @click="() => teacherListRemove(teacherRow)"
      />
    </a-form-item>
    <a-form-item v-bind="formItemLayoutWithOutLabel">
      <a-button
        type="dashed"
        style="width: 60%"
        @click="teacherListAdd"
      >
        <a-icon type="plus" />增加老师
      </a-button>
    </a-form-item>
    </a-form>
    
    </a-modal>
         <!-- 学生设置 -->
    <a-modal
      title="操作"
      :width="800"
      v-model="studentShow"
      @ok="handleStudent"
    > 
      <a-form :form="studentForm">
          
     <a-form-item
      v-for="(studentRow, index) in studentListData.studentList"
      :key="studentRow"
      v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
     >
          <a-select  
              v-model ='studentRow.studentId'
              allowClear
               placeholder="请输入学生名字"
            style="width: 30%; margin-right: 8px" > 
            <a-select-option 
             v-for="(studentOption,sindex) in studentOptions" :key="sindex"
              :value="studentOption.id" >{{studentOption.name}}</a-select-option> 
          </a-select>
         <a-select  
              v-model ='studentRow.positions'
              mode="multiple"
              @change="handleStudentPositionChange(value,pindex)" 
               placeholder="请输入学生职位"
        style="width: 60%; margin-right: 8px" >
               <a-select-option 
             v-for="(studentPositionOption,pindex) in studentPositionOptions" :key="pindex"
              :value="studentPositionOption.value" >{{studentPositionOption.name}}</a-select-option> 
          </a-select>     
      <a-icon
        class="dynamic-delete-button"
        type="minus-circle-o"
        @click="() => studentListRemove(studentRow)"
      />
    </a-form-item>
    <a-form-item v-bind="formItemLayoutWithOutLabel">
      <a-button
        type="dashed"
        style="width: 60%"
        @click="studentListAdd"
      >
        <a-icon type="plus" />增加学生
      </a-button>
    </a-form-item>
    </a-form>
    
    </a-modal>
  </a-card>
</template>

<script>
import STable from '@/components/table/'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import AInput from 'ant-design-vue/es/input/Input'
import moment from 'moment'

import { getRoleList, getClassList, editClass, addClass, getClass, delClass, getBuildingList, 
setClassTeacher, getTeacherOfClass, findSubject, findTeacher, findPosition, 
setClassStudent, getStudentOfClass, getChildrenSelect, getClassYearList, findYearList} from '@/api/manage'
let id = 0;
export default {
  name: 'ClassList',
  components: {
    AInput,
    ATextarea,
    STable
  },
  data() {
    return {
      visible: false,
      //        description: '全校班级管理。',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      },
      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '班级编号',
          dataIndex: 'no'
        },
        {
          title: '班级名称',
          dataIndex: 'name'
        },
        {
          title: '宣言',
          dataIndex: 'sign'
        },
        {
          title: '入学年份',
          dataIndex: 'year',
          sorter: (a, b) => a.year - b.year
        },
        {
          title: '人数',
          dataIndex: 'studentCount',
          needTotal: true,
          sorter: (a, b) => a.studentCount - b.studentCount
        },
        {
          title: '状态',
          dataIndex: 'type',
          customRender: text => {
            switch (text) {
              case 0:
                return '正常'
              case 1:
                return '已毕业'
              case 2:
                return '已锁定'
            }
          },
          filters: [
            {
              text: '正常',
              value: '0'
            },
            {
              text: '已毕业',
              value: '1'
            },
            {
              text: '已锁定',
              value: '2'
            }
          ],
          filterMultiple: false
        },
        {
          table: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getClassList(Object.assign(parameter, this.queryParam)).then(res => {
          return res.result
        })
      },

      selectedRowKeys: [],
      selectedRows: [],
      buildingOptions:[],
      building2Room:{},
      roomOptions:[], 
      // 教师设置参数
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24},
          sm: { span: 20},
        },
      },
       teacherShow: false,
       teacherForm: this.$form.createForm(this),
       teacherPositionOptions: [],
       teacherOptions: [],
       courseOptions: [],
       teacherListData : {
         teacherList: [],
         classId: null
       },
      //  学生设置参数
      studentShow: false,
       studentForm: this.$form.createForm(this),
      studentOptions: [],
      studentPositionOptions: [],
      studentListData : {
        studentList: [],
        classId: null
       },
       yearOptions: [],
       findYearOptions: []
    }
  },
 mounted(){
   
 },
  created() {
    getRoleList({ t: new Date() })  
     let self = this
     getClassYearList().then(res => {
        self.yearOptions = res.result.list
        self.year2Class = res.result.map
      }) 
    getBuildingList().then(res => {
        self.buildingOptions = res.result.list
        self.building2Room = res.result.map
      }) 
      findSubject().then(res => {
        self.courseOptions = res.result
      })
      findTeacher().then(res => {
        self.teacherOptions = res.result  
      })
      findPosition({type:"教师职位"}).then(res => {
        self.teacherPositionOptions = res
      })
       findPosition({type:"学生职位"}).then(res => {
        self.studentPositionOptions = res
      })
      getChildrenSelect().then(res => {
        self.studentOptions = res.result  
      })
      findYearList().then(res => {
        self.findYearOptions = res.result
      })
  },
  methods: {
       // 教师设置
    teacherSet(record){
      this.form.resetFields()
      this.teacherListData.classId = record.id;
      let self =this;
      getTeacherOfClass({id: record.id}).then(res => {
       if(res.success){
          //  self.teacherListData.teacherList = { ...res.result }
          self.teacherListData.teacherList = [];
          let that = self
          res.result.map( (item) => {
             that.teacherListData.teacherList.push({
              teacherId: item.teacherId,
              position: item.position,
               course: item.course
             });
          })
       }else {
          return
       }
      })
       this.teacherShow = true; 
    },
     teacherListRemove(teacherRow) {
      this.teacherListData.teacherList= this.teacherListData.teacherList.filter(key => key !== teacherRow)
    },

    teacherListAdd() { 
      this.teacherListData.teacherList.push({ 
      }) 
    },
    // 教师设置提交
    handleTeacher(e) {
     e.preventDefault()
      let self =this;
      let teacherValidate = true;
       this.teacherListData.teacherList.map((item)=>{
         if((typeof item.teacherId != 'undefined' ) && item.teacherId !=""){
           return
         } else {
           self.$message.error('请选择老师'); 
          teacherValidate = false
         }
         if((typeof item.position != 'undefined' ) && item.position >0){
           return
         } else {
           self.$message.error('请选择职位'); 
          teacherValidate = false
         }
         if(item.position > 1){
           if(!(item.course > 0)){
            self.$message.error('请选择科目'); 
            teacherValidate = false
           } 
         }
      })
      if(!teacherValidate){
       return ;
     } else {
       console.log(this.teacherListData)
       let setTeacherData = JSON.stringify(this.teacherListData.teacherList)
        setClassTeacher({teacherList:setTeacherData, classId: self.teacherListData.classId}).then(res => {
              if(res.success){
                self.$message.success('设置成功')
                self.teacherShow = false; 
              }else{
              self.$message.error(res.message)
           }      
       })
     }
    },
      // 学生设置
    studentSet(record){
          this.form.resetFields()
      this.studentListData.classId = record.id;
      let self =this;
      getStudentOfClass({id: record.id}).then(res => {
       if(res.success){
          self.studentListData.studentList = [];
          let that = self
          res.result.map( (item) => {
             that.studentListData.studentList.push({
              studentId: item.studentId,
              positions: item.positions
             });
          })
       }else {
          return
       }
      })
       this.studentShow = true; 
    },
     studentListRemove(studentRow) {
      this.studentListData.studentList= this.studentListData.studentList.filter(key => key !== studentRow)
    },

    studentListAdd() { 
      this.studentListData.studentList.push({ 
      }) 
    },
    
     handleStudentPositionChange(value,pindex) {
      console.log(value,pindex);
      let self = this
      this.studentListData.studentList[pindex].positions = value;
    },
    // 学生设置提交
    handleStudent(e) {
     e.preventDefault()
      let self =this;
      let studentValidate = true;
       this.studentListData.studentList.map((item)=>{
         if((typeof item.studentId != 'undefined' ) && item.studentId !=""){
           return
         } else {
           self.$message.error('请选择学生'); 
          studentValidate = false
         }
         if((typeof item.positions != 'undefined' ) && item.positions.length!=0){
           return
         } else {
           self.$message.error('请选择职位'); 
           studentValidate = false
         }
      })
      if(!studentValidate){
       return ;
     } else {
       console.log(this.studentListData)
       let setStudentData = JSON.stringify(this.studentListData.studentList)
        setClassStudent({studentList: setStudentData, classId: self.studentListData.classId}).then(res => {
              if(res.success){
                self.$message.success('设置成功')
                self.studentShow = false; 
              }else{
              self.$message.error(res.message)
           }      
       })
     }
    },




    // 增
    handleAdd() {
      this.visible = true
      this.form.resetFields()
    },
    // 改
    handleEdit(record) {
       this.form.resetFields()
      let self = this
      getClass({ id: record.id }).then(res => {
        self.form.setFieldsValue({ ...res.result })
        let classroomId = res.result.classroomId;
        console.log(this.classroomId,self.building2Room)
        let buidingKeys = Object.keys(self.building2Room);
        console.log('buidingKeys')
        console.log(buidingKeys)
        buidingKeys.map((buildingKey) => { 
          self.building2Room[buildingKey].map((room) => {
            if(room.id == classroomId){ 
              self.form.setFieldsValue({buiding_id: buildingKey}) 
              self.roomOptions = self.building2Room[buildingKey]
              self.form.setFieldsValue({classroomId: room.id})
            }
          })
        })
      }) 
      this.visible = true
    },
     handleBuildingChange(value){  
      let self = this;
      self.roomOptions = this.building2Room[value]
      self.form.setFieldsValue({room_id: self.roomOptions[0].id})
      //this.secondCity = cityData[value][0]
    },
    // 增改 处理
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          if (values.id) {
            let self = this
            editClass(values).then(res => {
               if(res.success){
                self.$message.success('修改成功')
                self.$refs.table.refresh(true)
                self.visible = false
              }else{
                self.$message.error(res.message)
              } 
            })
          } else {
            let self = this
            addClass(values).then(res => {
               if(res.success){
                self.$message.success('添加成功')
                self.$refs.table.refresh(true)
                self.visible = false
              }else{
                self.$message.error(res.message)
              }  
            })
          }
        }
      })
    },
    
    
    // 删
    delConfirm(record) {
      console.log(record)
      let self = this
      delClass({ ids: record.id }).then(res => {
        console.log(res)
        self.$message.success('删除成功')
        self.$refs.table.refresh(true)
      })
    },
    // 查
    onSearch() {
      let self = this
      getClassList(this.queryParam).then(res => {
        self.$refs.table.refresh(true)
      })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },

    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    },

  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>